package org.yoyo.game.decoder;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;
import org.yoyo.game.packet.UserPacket;

public class UserDecoder implements MessageDecoder{

	
	@Override
	public MessageDecoderResult decodable(IoSession session, IoBuffer buffer) {
		System.out.println("[UserDecoder] [decodable] [buffer:"+buffer+"] [session:"+session+"] ");
		
		if(buffer.remaining()<8)
			return MessageDecoderResult.NEED_DATA;
		
		byte version = buffer.get();
		short command = buffer.getShort();
		byte type = buffer.get();
		int length = buffer.getInt();
		byte key = buffer.get();
		
		System.out.println("[UserDecoder] [decodable] [version:"+version+"] [command:"+command+"]" +
				"[type:"+type+"][length:"+length+"] [key:"+key+"]");
		
		if(buffer.remaining()<length)
			return MessageDecoderResult.NEED_DATA;
		
		if(key==version+type)
			return MessageDecoderResult.OK;
		
		return MessageDecoderResult.NOT_OK;
	}

	@Override
	public MessageDecoderResult decode(IoSession session, IoBuffer buffer,
			ProtocolDecoderOutput output) throws Exception {
		
		System.out.println("[UserDecoder] [decode] [session:"+session+"] [buffer:"+buffer+"]");
		
		UserPacket packet = new UserPacket();
		packet.setVersion(buffer.get());
		packet.setCommond(buffer.getShort());
		packet.setType(buffer.get());
		packet.setLength(buffer.getInt());
		packet.setKey(buffer.get());
		
		Charset set = Charset.forName("GBK");
		CharsetDecoder decoder = set.newDecoder();
		packet.setData(buffer.getString(packet.getLength(),decoder));
		
		System.out.println("[UserDecoder] [decode] [userpacket:"+packet+"] [session:"+session+"] ");
		
		return MessageDecoderResult.OK;
	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput output)
			throws Exception {
		
	}

}
